package com.allwees.bs.c.module.ops.service.impl;

import com.allwees.bs.c.module.ops.entity.PromoActiveDefEntity;
import com.allwees.bs.c.module.ops.repository.PromoActiveDefRepository;
import com.allwees.bs.c.module.ops.service.PromoUseService;
import com.allwees.bs.c.module.user.entity.UserEntity;
import com.allwees.bs.c.module.user.entity.UserPromoLogEntity;
import com.allwees.bs.c.module.user.repository.UserPromoLogRepository;
import com.allwees.bs.c.module.user.service.IUserService;
import com.allwees.bs.core.model.coupon.constant.EPromoUseType;
import com.allwees.core.common.constant.EStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author mouhaining
 * @since 2020-05-25 15:43
 */
@Slf4j
@Service
public class PromoUseServiceImpl implements PromoUseService {

    @Autowired
    private PromoActiveDefRepository promoActiveDefRepository;
    @Autowired
    private UserPromoLogRepository userPromoLogRepository;
    @Autowired
    private IUserService userService;

    @Override
    public UserPromoLogEntity findByLogUuid(String logUuid) {
        return userPromoLogRepository.findByUuid(logUuid);
    }

    @Override
    public UserPromoLogEntity receiveAndUse(String userUuid, String promoCode) {
        UserEntity user = userService.findByPromoCode(promoCode);
        if (user == null) {
            return null;
        }

        PromoActiveDefEntity promoActiveDef = promoActiveDefRepository.findByUseType(EPromoUseType.USER_PROMO_CODE);
        List<UserPromoLogEntity> logs = userPromoLogRepository.findByUserUuidAndUseType(userUuid, EPromoUseType.USER_PROMO_CODE);
        if (promoActiveDef == null || promoActiveDef.getSingleUserReceiveMaxCount() <= logs.size()) {
            return null;
        }

        UserPromoLogEntity userPromoLog = new UserPromoLogEntity(userUuid, promoCode, user.getUuid(), promoActiveDef);
        userPromoLogRepository.save(userPromoLog);

        return userPromoLog;
    }

    @Override
    public void completed(String userCouponUuid) {
        UserPromoLogEntity userPromoLog = userPromoLogRepository.findByUuid(userCouponUuid);
        if (!EStatus.USED.equals(userPromoLog.getEStatus())) {
            return;
        }
        userPromoLog.setEStatus(EStatus.COMPLETED);
        userPromoLogRepository.save(userPromoLog);
    }
}
